<script lang="ts" setup>
import { ref, watch, computed, onMounted } from 'vue';
import { getGroupList, IGroup } from '@/api/group';
import TablePersonCard from '@/components/Person/TablePersonCard.vue';
import router from '@/router';

const activeKey = ref('1');
const tabs = ['已加入的团队', '我创建的团队', '所有团队'];
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const sorterField = ref<string | null>(null);
const sorterOrder = ref<string | null>(null);

const columns = [
  {
    title: '团队名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '介绍',
    dataIndex: 'introduction',
    key: 'introduction',
  },
  {
    title: '成员数量',
    dataIndex: 'memberCount',
    key: 'memberCount',
    sorter: true,
    align: 'center',
  },
  {
    title: '创建者',
    dataIndex: ['creator', 'username'],
    key: 'creator',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    sorter: true,
  },
];

const dataSource = ref<IGroup[]>();
const loading = ref(false);

const pagination = computed(() => ({
  total: total.value,
  current: currentPage.value,
  pageSize: pageSize.value,
  showSizeChanger: true,
  showQuickJumper: true,
}));

type APIParams = {
  type: string;
  page: number;
  // eslint-disable-next-line camelcase
  page_size: number;
  sortField?: string | null;
  sortOrder?: string | null;
};

const fetchData = async (params: APIParams) => {
  loading.value = true;
  try {
    const response = await getGroupList(params);
    dataSource.value = response.list.results;
    total.value = response.list.count;
  } catch (error) {
    console.error('Error fetching data:', error);
  } finally {
    loading.value = false;
  }
};

const handleTableChange = (
  pagination: { current: number; pageSize: number },
  filters: any,
  sorter: any
) => {
  currentPage.value = pagination.current;
  pageSize.value = pagination.pageSize;

  sorterField.value = sorter.field || null;
  sorterOrder.value = sorter.order || null;

  fetchData({
    type: getType(activeKey.value),
    page: currentPage.value,
    page_size: pageSize.value,
    sortField: sorter.field,
    sortOrder: sorter.order,
    ...filters,
  });
};

const getType = (key: string) => {
  if (key === '1') return 'joined';
  if (key === '2') return 'created';
  return 'public';
};

const goGroupHome = async (id: number) => {
  await router.push({
    name: 'GroupHome',
    params: {
      groupId: id,
    }
  });
};


// 初次加载时获取数据
onMounted(() => {
  fetchData({ type: getType(activeKey.value), page: currentPage.value, page_size: pageSize.value });
});

// 监听 activeKey 和 currentPage 的变化
watch([activeKey, currentPage], ([newKey, newPage]) => {
  fetchData({
    type: getType(newKey),
    page: newPage,
    page_size: pageSize.value,
    sortField: sorterField.value,
    sortOrder: sorterOrder.value,
  });
});
</script>

<template>
  <a-row type="flex" justify="center">
    <a-col :xs="23" :sm="23" :md="20" :lg="18" :xl="18">
      <h1>团队列表</h1>
      <a-tabs v-model:activeKey="activeKey" size="large">
        <a-tab-pane key="1" :tab="tabs[0]">
          <a-table
            :columns="columns"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            row-key="id"
            @change="handleTableChange">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'name'">
                <a type="link" class="link-primary text-decoration-none" @click="goGroupHome(record.teamDetail)">
                  {{ text }}
                </a>
              </template>
              <template v-if="column.dataIndex === 'introduction'" >
                <div class="d-inline-block text-truncate" style="max-width: 200px;"> {{ text }}</div>
              </template>
              <template v-if="column.key === 'creator'">
                <table-person-card :person="record.creator"/>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" :tab="tabs[1]">
          <a-table
            :columns="columns"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            row-key="id"
            @change="handleTableChange"
          >
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'name'">
                <a type="link" class="link-primary text-decoration-none" @click="goGroupHome(record.teamDetail)">
                  {{ text }}
                </a>
              </template>
              <template v-if="column.dataIndex === 'introduction'" >
                <div class="d-inline-block text-truncate" style="max-width: 200px;"> {{ text }}</div>
              </template>
              <template v-if="column.key === 'creator'">
                <table-person-card :person="record.creator"/>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="3" :tab="tabs[2]">
          <a-table
            :columns="columns"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            row-key="id"
            @change="handleTableChange"
          >
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'name'">
                <a type="link" class="link-primary text-decoration-none" @click="goGroupHome(record.teamDetail)">
                  {{ text }}
                </a>
              </template>
              <template v-if="column.dataIndex === 'introduction'" >
                <div class="d-inline-block text-truncate" style="max-width: 200px;"> {{ text }}</div>
              </template>
              <template v-if="column.key === 'creator'">
                <table-person-card :person="record.creator"/>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-col>
  </a-row>
</template>
<style scoped lang="less">
</style>
